<template>
  <div class="hand-sign-box" :class="{ disabled }" :style="{ width }" @click="openSignature">
    <el-link
      type="info"
      :underline="false"
      class="hand-sign"
      v-if="signatureValue == null || signatureValue === ''"
    >
      <el-icon><Edit /></el-icon>
      <span>添加签名</span>
    </el-link>
    <div class="sign-preview" v-else>
      <div class="preview-delete-icon" @click.stop="deleteSignature">
        <el-icon><Delete /></el-icon>
      </div>
      <img :src="signatureValue" alt="签名" :style="{ height }" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { Dialog } from '@/components/Dialog';
import SignaturePad from './signatureDlg.vue';
import { SignatureInfo } from './signature';
import { useLoginStore } from '@/store';
import SystemUserController from '@/api/system/UserController';
import { ref, watch, onMounted } from 'vue';

const emit = defineEmits<{
  'update:modelValue': [string | undefined];
  change: [string | undefined];
}>();
interface IProps {
  modelValue?: string;
  width?: string | number;
  height?: string | number;
  disabled?: boolean;
  backgroundColor?: string;
  penColor?: string;
  autoTrim?: boolean;
}

const props = withDefaults(defineProps<IProps>(), {
  width: '100%',
  height: '200px',
  penColor: '#000000',
  autoTrim: true,
});

const loginStore = useLoginStore();
const signatureValue = ref(props.modelValue);

// Watch for changes in modelValue
watch(
  () => props.modelValue,
  newValue => {
    signatureValue.value = newValue;
  },
);

// Function to fetch signature from API if needed
const fetchSignatureIfNeeded = async () => {
  // If there's no signature value and we need to use the default
  if (!signatureValue.value) {
    // First try to get from userInfo
    if (loginStore.userInfo?.signatureData) {
      signatureValue.value = loginStore.userInfo.signatureData;
    } else {
      // If not in userInfo, call API to get it
      try {
        const response = await SystemUserController.getUserSignature({});
        if (response.data && typeof response.data === 'string') {
          signatureValue.value = response.data;
          // Update userInfo with the signature data if we found it
          if (loginStore.userInfo && signatureValue.value) {
            loginStore.userInfo.signatureData = signatureValue.value;
          }
        } else {
          signatureValue.value = '';
        }
        emit('update:modelValue', signatureValue.value);
        emit('change', signatureValue.value);
      } catch (error) {
        console.error('Failed to fetch user signature:', error);
        signatureValue.value = '';
      }
    }
  }
};

onMounted(() => {
  fetchSignatureIfNeeded();
});

const openSignature = () => {
  if (props.disabled) return;
  Dialog.show<SignatureInfo>(
    '手写签名',
    SignaturePad,
    {
      area: ['600px'],
    },
    {
      value: signatureValue.value,
      width: '100%',
      height: '300px',
      autoTrim: props.autoTrim, // 自动裁剪到签名实际大小，默认为true
      backgroundColor: props.backgroundColor,
      penColor: props.penColor,
    },
  ).then(res => {
    signatureValue.value = res.data;
    emit('update:modelValue', res.data);
    emit('change', res.data);
  });
};

const deleteSignature = () => {
  ElMessageBox.confirm(`确定要删除此签名吗？`, '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      signatureValue.value = undefined;
      emit('update:modelValue', undefined);
      emit('change', undefined);
    })
    .catch(e => {
      console.log(e);
    });
};
</script>

<style scoped>
.hand-sign-box .hand-sign {
  width: 100%;
  background-color: #f7f7f7;
  text-align: left;
  -webkit-box-pack: left;
  -ms-flex-pack: left;
  justify-content: left;
  padding: 0 10px;
}
.hand-sign-box .hand-sign i {
  margin-right: 4px;
  position: relative;
  top: 1px;
}
.hand-sign-box .hand-sign:hover {
  background-color: #efefef;
}
.hand-sign-box.disabled .hand-sign:hover {
  cursor: not-allowed;
}

.hand-sign-box .sign-preview {
  position: relative;
  min-height: 100px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  border: 1px solid #dcdfe6;
  padding: 8px 0;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.hand-sign-box .sign-preview img {
  max-width: 100%;
  cursor: pointer;
}
.hand-sign-box .sign-preview .preview-delete-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  background-color: #ffffff;
  cursor: pointer;
  border-radius: 50%;
  -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
  display: none;
}
.hand-sign-box .sign-preview .preview-delete-icon:hover {
  -webkit-box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
}
.hand-sign-box .sign-preview:hover .preview-delete-icon,
.hand-sign-box.is-mobile .preview-delete-icon {
  display: block;
}
</style>
